#!/usr/bin/env python3
import json
import os
import re
import sys
import traceback

import color

from apkleaks.colors import color as col

class util:
	@staticmethod
	def write(message, color):
		sys.stdout.write("%s%s%s" % (color, message, col.ENDC))

	@staticmethod
	def writeln(message, color):
		util.write(message + "\n", color)

# 	@staticmethod
# 	def finder(pattern, path):
# 		matcher = re.compile(pattern)
# 		found = []
# 		for fp, dirname, files in os.walk(path):
# 			# dirname是一个列表
# 			# util.write(dirname.__str__() + "\n", col.OKGREEN)
# 			util.write(fp + "\n", col.OKGREEN)
# 			for fn in files:
# 				filepath = os.path.join(fp, fn)
# 				util.writeln(filepath, col.OKBLUE)
# 				with open(filepath) as handle:
# 					try:
# 						for line in handle.readlines():
# 							mo = matcher.search(line)
# 							if mo:
# 								found.append(mo.group())
# 					except Exception:
# 						pass
# 		return sorted(list(set(found)))
class find_format:
	def __init__(self):
		self.url_dict = {}
		self.prefix_dict = {
			"cloud": "https://test-online.vesync.com",
			"operation": "https://testonline-store.vesync.com/",
			"store": "https://testonline-operationapi.vesync.com"
		}
		self.result = {
			"https://test-online.vesync.com": {
				"post": [],
				"get": [],
				"put": [],
				"delete": []
			}
			,
			"https://testonline-store.vesync.com/": {
				"post": [],
				"get": [],
				"put": [],
				"delete": []
			}
			,
			"https://testonline-operationapi.vesync.com": {
				"post": [],
				"get": [],
				"put": [],
				"delete": []
			},
			"others": []
		}
	@staticmethod
	def write(message, color):
		sys.stdout.write("%s%s%s" % (color, message, '\033[1m'))
	def extractUrl(self, input_str):
		match = re.search(r'@ServerUrlTag\("([^"]+)"\)', input_str)
		if match:
			extracted_string = match.group(1)
			return extracted_string  # 输出: cloud
		else:
			return ""
	def extract_suffix(self, in_str):
		pattern = r'@*\("([^"]+)"\)'
		match = re.search(pattern, in_str)
		if match:
			return match.group(1)
		return ""
	def find_other(self, path):
		url_pattern = re.compile(r'https?://[^\s/$?#]*vesync\.com[^\s"]+')
		for fp, dirname, files in os.walk(path):
			# util.write(dirname.__str__() + "\n", col.OKGREEN)
			# self.write(fp + "\n", col.OKGREEN)
			for fn in files:
				filepath = os.path.join(fp, fn)
				with open(filepath, encoding='utf-8') as handle:
					try:
						for line in handle.readlines():
							mo = url_pattern.search(line)
							if mo is not None:
								self.result["others"].append(mo.group())
					except Exception:
						traceback.print_exc()

	def finder(self, pattern, path_list, name):
		matcher = re.compile(pattern)
		for path in path_list:
			for fp, dirname, files in os.walk(path):
				# util.write(dirname.__str__() + "\n", col.OKGREEN)
				# self.write(fp + "\n", col.OKGREEN)
				for fn in files:
					filepath = os.path.join(fp, fn)
					with open(filepath, encoding="utf-8") as handle:
						try:
							for line in handle.readlines():
								mo = matcher.search(line)
								if mo:
									if mo.group().__contains__("@ServerUrlTag"):
										#以路径所在的文件全路径为键 请求url前缀为值放入字典中
										a = mo.group()
										self.url_dict[filepath] = self.prefix_dict[self.extractUrl(a)]
									else:
										a = self.extract_suffix(mo.group())
										# 如果没有请求serverurltag 则说明是旧的网络库
										if filepath not in self.url_dict:
											self.result["https://test-online.vesync.com"][name].append(a)
										else:
											self.result[self.url_dict[filepath]][name].append(a)
						except Exception:
							traceback.print_exc()
			self.find_other(path)
		# self.format_result(self.result)
		return self.result